import {login, getInfo, getNettyServerAddr,logout} from '_a/user'
import {getToken, setToken, removeToken} from '@/libs/auth'

const state = {
    token: getToken(),
    id: null,
    name: null,
    phone: null,
    nettyAddr: null
}

const mutations = {
    SET_TOKEN: (state, token) => {
        setToken(token)
        state.token = token
    },
    SET_ID: (state, id) => {
        state.id = id
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_PHONE: (state, phone) => {
        state.phone = phone
    },
    SET_NETTY_ADDR: (state, nettyAddr) => {
        state.nettyAddr = nettyAddr
    },
}

const actions = {
    // user login
    login({commit}, userInfo) {
        return new Promise((resolve, reject) => {
            login(userInfo).then(response => {
                const {data} = response
                commit('SET_TOKEN', data)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // get user info
    getInfo({commit, state}) {
        return new Promise((resolve, reject) => {
            getInfo().then(response => {
                const {data} = response

                if (!data) {
                    reject('Verification failed, please Login again.')
                }
                commit('SET_ID', data.id)
                commit('SET_NAME', data.username)
                commit('SET_PHONE', data.phone)
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },

    getNettyServerAddr({commit, state}) {
        return new Promise((resolve, reject) => {
            getNettyServerAddr().then(response => {
                const {data} = response
                commit('SET_NETTY_ADDR', data)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },
    // user logout
    logout({commit, state, dispatch}) {
        return new Promise((resolve, reject) => {
            /*commit('SET_TOKEN', null)
            commit('SET_NETTY_ADDR', null)
            commit('SET_ID', null)
            commit('SET_NAME', null)
            removeToken()
            resolve()*/
            logout(state.id).then(res => {
                if (res.code == 200){
                    commit('SET_TOKEN', null)
                    commit('SET_NETTY_ADDR', null)
                    commit('SET_ID', null)
                    commit('SET_NAME', null)
                    removeToken()
                    resolve()
                }
            }).catch(error => {
                reject(error)
            })
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
